import React, { useEffect, memo, useMemo } from 'react';
import { Row, Col, Drawer } from 'antd';
import styles from './index.less';
import vkbeautify from 'vkbeautify';
import CodeMirror from '../../../MessageTemplate/components/xmlEdit/codeMirror.jsx';
import useModel from '../../useModels/useModel.js';
import moment from 'moment';

const IssuedMessage = memo(() => {
  const {
    issueMessage,
    setIssueMessage,
    state: { issueErrorResult },
  } = useModel(model => [model.issueMessage, model.state.issueErrorResult]);
  useEffect(() => {
    return () => {
      setIssueMessage({});
    };
  }, []);
  //请求报文
  let requestXML = issueMessage.request
    ? vkbeautify.xml(issueMessage.request.replace(/\s/g, ' '))
    : '';
  //响应报文
  let responseXML = issueMessage.response
    ? vkbeautify.xml(issueMessage.response.replace(/\s/g, ' '))
    : '';
  let requestLineWidget = {};
  let responseLineWidget = {};
  if (issueErrorResult && JSON.stringify(issueErrorResult) !== '{}') {
    const errorDes = issueErrorResult.description;
    let lineWidgetObject = {
      lineWidget: (errorDes?.details || []).map(item => {
        return {
          line: item.number,
          message: item.msg,
        };
      }),
    };
    if (issueErrorResult.response) {
      responseLineWidget = lineWidgetObject;
      responseXML = errorDes.xml;
    } else {
      requestLineWidget = lineWidgetObject;
      requestXML = errorDes.xml;
    }
  }

  return (
    <Row gutter={[12, 0]} className={styles['issued-message-wrap']}>
      <Col span={12} className={styles['request']}>
        <div className={styles['ct']}>
          <div className={styles['title']}>
            <span>请求报文内容</span>
            {issueMessage.customName && issueMessage.time && (
              <span className={styles['suName']}>{`(${issueMessage.suId} => ${
                issueMessage.customName
              } => ${moment(issueMessage.time).format('YYYY-MM-DD HH:mm:ss')})`}</span>
            )}
          </div>
          <div className={styles['editor']}>
            <CodeMirror code={requestXML} readOnly={true} {...requestLineWidget} />
          </div>
        </div>
      </Col>
      <Col span={12} className={styles['response']}>
        <div className={styles['ct']}>
          <div className={styles['title']}>
            <span>响应报文内容</span>
            {issueMessage.customName && issueMessage.time && (
              <span className={styles['suName']}>{`(${issueMessage.suId} => ${
                issueMessage.customName
              } => ${moment(issueMessage.time).format('YYYY-MM-DD HH:mm:ss')})`}</span>
            )}
          </div>
          <div className={styles['editor']}>
            <CodeMirror code={responseXML} readOnly={true} {...responseLineWidget} />
          </div>
        </div>
      </Col>
    </Row>
  );
});

export default IssuedMessage;
